package com.jinzecloud.reportapproval.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.jinzecloud.reportapproval.bean.HandoverChecklist;
import com.jinzecloud.reportapproval.bean.KeyInstrument;
import com.jinzecloud.reportapproval.bean.KeyInstrumentDetail;
import com.jinzecloud.reportapproval.bean.SampleSheet;
import com.jinzecloud.reportapproval.dto.AdminDto;
import com.jinzecloud.reportapproval.dto.AuditParam;
import com.jinzecloud.reportapproval.dto.DataStagingParam;
import com.jinzecloud.reportapproval.enums.AuditRoleEnums;
import com.jinzecloud.reportapproval.enums.StateEnum;
import com.jinzecloud.reportapproval.enums.TableEnums;
import com.jinzecloud.reportapproval.mapper.HandoverChecklistMapper;
import com.jinzecloud.reportapproval.service.HandoverChecklistService;
import com.jinzecloud.reportapproval.utils.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.ParseException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class HandoverChecklistServiceImpl extends ServiceImpl<HandoverChecklistMapper, HandoverChecklist> implements HandoverChecklistService {

    private final FileUploadUtil fileUploadUtil;
    @Autowired
    private HttpServletRequest request;

    @Override
    public R audit(AuditParam auditParam) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        List<AdminDto> adminDos = AuditUtil.getAdminDto(authentication.getName());
        if (CollectionUtil.isEmpty(adminDos)) return R.error("您没有审核权限！");
        HandoverChecklist handoverChecklist = this.getById(auditParam.getId());
        int state = handoverChecklist.getState();
        if (!auditParam.isState()) {
            updateById(handoverChecklist.setState(StateEnum.APPROVAL_NOT_PASS.getState())
                    .setAuditOpinion(auditParam.getAuditOpinion())
                    .setAuditDate(DateUtil.date()));
            return R.ok();
        }
        StateEnum currentAuditState = AuditUtil.getStateText(TableEnums.HANDOVER_CHECK_LIST.getTableName(), state);
        Integer nextAuditStateIndex = AuditUtil.getNextAuditState(TableEnums.HANDOVER_CHECK_LIST.getTableName(), state, adminDos.stream().map(AdminDto::getRoleCode).toList());        AdminDto adminDto = adminDos.stream().filter(a -> StrUtil.equals(a.getRoleCode(), currentAuditState.getAuditRole()))
                .findFirst().orElse(null);
        if (adminDto == null || nextAuditStateIndex == null) return R.error("您没有审核权限！");
        if (StrUtil.equals(adminDto.getRoleCode(), AuditRoleEnums.TRANSFER_PERSON.getCode())) handoverChecklist.setHandoverPerson(adminDto.getAdSignature());
        if (StrUtil.equals(adminDto.getRoleCode(), AuditRoleEnums.RECEIVER.getCode())) handoverChecklist.setReceiver(adminDto.getAdSignature());
        handoverChecklist.setState(nextAuditStateIndex)
                .setAuditOpinion(auditParam.getAuditOpinion())
                .setAuditDate(DateUtil.date());
        updateById(handoverChecklist);
        return R.ok();
    }

    @Override
    public Object auditList(DataStagingParam param) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LambdaQueryWrapper<HandoverChecklist> queryWrapper = new LambdaQueryWrapper<>();
        List<AdminDto> adminDto = AuditUtil.getAdminDto(authentication.getName());
        Set<Integer> roleSet = adminDto.stream().map(a -> StateEnum.getStateEnumByAuditRole(a.getRoleCode()).getState()).collect(Collectors.toSet());
        roleSet.remove(StateEnum.UN_SUBMIT.getState());
        queryWrapper.in(HandoverChecklist::getState, AuditUtil.getCurrentStateIndex(TableEnums.SAMPLE_SHEET.getTableName(), roleSet));
        queryWrapper.and(w -> w.like(param.getSearchKey() != null, HandoverChecklist::getProjectNumber, param.getSearchKey())
                .or().like(param.getSearchKey() != null, HandoverChecklist::getProductName, param.getSearchKey())
                .or().like(param.getSearchKey() != null, HandoverChecklist::getHandoverPerson, param.getSearchKey()));
        return page(new Page<>(param.getPageNo(), param.getPageSize()), queryWrapper);
    }

    public String fileDownload(HandoverChecklist handoverChecklist, HttpServletRequest request) {
        JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(handoverChecklist, JSONWriter.Feature.NullAsDefaultValue.ordinal()));
        File tempFile = WordUtil.getWordFile("template/handoverChecklist.docx", data, Configure.builder()
                .useSpringEL(true)
        );
        if (tempFile == null) return null;
        String fileName = "资料移交清单";
        String uploadDirectory = fileUploadUtil.getUploadFilePath("temp");
        String filePath = uploadDirectory + handoverChecklist.getId() + fileName;
        String savePath = RequestUtils.getBasePath(request) + "upload/temp/" + handoverChecklist.getId() +fileName;
        FileUtil.copy(tempFile, new File(filePath + ".docx"), true);
        PDFUtil.WordToPdf(tempFile, new File(filePath + ".pdf"));
        this.update(new LambdaUpdateWrapper<HandoverChecklist>().set(HandoverChecklist::getWordPath, savePath + ".docx")
                .set(HandoverChecklist::getPdfPath, savePath + ".pdf").eq(HandoverChecklist::getId, handoverChecklist.getId()));
        return RequestUtils.getBasePath(request) + "upload/temp/" + handoverChecklist.getId() + fileName + ".pdf";
    }

    public String fileDownloadWord(HandoverChecklist handoverChecklist, HttpServletRequest request) {
        JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(handoverChecklist, JSONWriter.Feature.NullAsDefaultValue.ordinal()));
        File tempFile = WordUtil.getWordFile("template/handoverChecklist.docx", data, Configure.builder()
                .useSpringEL(true)
        );
        if (tempFile == null) return null;
        String fileName = "资料移交清单";
        String uploadDirectory = fileUploadUtil.getUploadFilePath("temp");
        String filePath = uploadDirectory + handoverChecklist.getId() + fileName;
        String savePath = RequestUtils.getBasePath(request) + "upload/temp/" + handoverChecklist.getId() +fileName;
        FileUtil.copy(tempFile, new File(filePath + ".docx"), true);
        PDFUtil.WordToPdf(tempFile, new File(filePath + ".pdf"));
        this.update(new LambdaUpdateWrapper<HandoverChecklist>().set(HandoverChecklist::getWordPath, savePath + ".docx").set(HandoverChecklist::getPdfPath, savePath + ".pdf").eq(HandoverChecklist::getId, handoverChecklist.getId()));
        return RequestUtils.getBasePath(request) + "upload/temp/" + handoverChecklist.getId() + fileName + ".docx";
    }

    @Override
    public String getFilePath(String id, HttpServletRequest request) {
        HandoverChecklist handoverChecklist = getById(id);
        if (StrUtil.isEmpty(handoverChecklist.getWordPath()) || StrUtil.isEmpty(handoverChecklist.getPdfPath())){
            return fileDownload(handoverChecklist, request);
        }
        return handoverChecklist.getPdfPath();
    }

    @Override
    public String viewPdf(Integer id) {
        HandoverChecklist handoverChecklist = getById(id);
//        String dataTime = handoverChecklist.get();
//        try {
//            keyInstrument.setDataTime(sdf.format(inputFormat.parse(dataTime)));
//        } catch (ParseException e) {
//            throw new RuntimeException(e);
//        }
        List<HandoverChecklist> keyInstrumentDetailList = this.list(new QueryWrapper<HandoverChecklist>().eq("id", id).orderByAsc("id"));
//        HandoverChecklist.setDetailList(keyInstrumentDetailList);
        String s = fileDownload(handoverChecklist, request);
        return s;
    }

    @Override
    public R saveHandoverChecklist(HandoverChecklist handoverChecklist) {
        QueryWrapper<HandoverChecklist> handoverChecklistQueryWrapper = new QueryWrapper<>();
        handoverChecklistQueryWrapper.eq("project_number", handoverChecklist.getProjectNumber());
        List<HandoverChecklist> list = this.list(handoverChecklistQueryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            return R.error("项目编号已存在");
        }
        this.save(handoverChecklist);
        return R.ok();
    }

    @Override
    public String viewWord(Integer id) {
        HandoverChecklist handoverChecklist = getById(id);
//        String dataTime = handoverChecklist.get();
//        try {
//            keyInstrument.setDataTime(sdf.format(inputFormat.parse(dataTime)));
//        } catch (ParseException e) {
//            throw new RuntimeException(e);
//        }
        List<HandoverChecklist> keyInstrumentDetailList = this.list(new QueryWrapper<HandoverChecklist>().eq("id", id).orderByAsc("id"));
//        HandoverChecklist.setDetailList(keyInstrumentDetailList);
        String s = fileDownloadWord(handoverChecklist, request);
        return s;
    }
}
